package com.yuerenjf.yuerenjinfu.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.activity.MainActivity;
import com.yuerenjf.yuerenjinfu.activity.WebActivity;
import com.yuerenjf.yuerenjinfu.adapter.AdapterFindReport;
import com.yuerenjf.yuerenjinfu.adapter.AdapterFindTop;
import com.yuerenjf.yuerenjinfu.adapter.AdapterTogether;
import com.yuerenjf.yuerenjinfu.bean.BaseFindBean;
import com.yuerenjf.yuerenjinfu.bean.FindTabBean;
import com.yuerenjf.yuerenjinfu.bean.FindTogetherBean;
import com.yuerenjf.yuerenjinfu.customview.AutoVerticalScrollTextView;
import com.yuerenjf.yuerenjinfu.customview.ExpandGridView;
import com.yuerenjf.yuerenjinfu.customview.ExpandListView;
import com.yuerenjf.yuerenjinfu.customview.MyPtrClassicFrameLayout;
import com.yuerenjf.yuerenjinfu.http.Constants;
import com.yuerenjf.yuerenjinfu.http.Xutils;
import com.yuerenjf.yuerenjinfu.utils.MyDisplayImageOptions;

import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/6/13.
 */
public class FragmentFind extends BaseFragment {
    MyPtrClassicFrameLayout myPtrClassicFrameLayout;

    private int mTogetherRes[] = {
            R.drawable.icon_operate_huaxing, R.drawable.icon_operate_fadada, R.drawable.icon_operate_ali, R.drawable.icon_operate_didi
    };

    private HandlerThread mCheckMsgThread;
    private boolean isUpdateInfo;
    private int number;
    private static final int MSG_UPDATE_INFO = 0x110;
    //与UI线程管理的handler
    private Handler mHandler = new Handler();

    Handler mCheckMsgHandler;
    private ExpandGridView topGridView;

    private AutoVerticalScrollTextView mScrollNewsTextView;
    private TextView mScrollNewsAllView;
    private LinearLayout mActivityLayout;
    private TextView mActionAllTv;//查看活动全部
    private TextView mActionTitleTv;
    private TextView mActionDescTv;
    private ImageView mActionImageView;

    private TextView mMedioReportAllTv;
    private ExpandListView mMedioReportExpandListView;

    private TextView mTogetherAllTv;
    private ExpandGridView mTogetherExpandGridView;

    List<FindTabBean.NewDynamiBean> mNewDynamiBean;

    private String mUrlAllNews;//
    private String mUrlAllAction;
    private String mUrlAllReport;
    private String mUrlAllTogether;

    @Override
    public void prepareData() {

    }


    @Override
    public View prepareView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_find, null);
        initView(view);
        LogUtil.i("prepareView");
        return view;
    }

    private void initView(View view) {

        myPtrClassicFrameLayout = (MyPtrClassicFrameLayout) view.findViewById(R.id.MyPtrClassicFrameLayout);
        topGridView = (ExpandGridView) view.findViewById(R.id.top_expandGridView);

        mScrollNewsTextView = (AutoVerticalScrollTextView) view.findViewById(R.id.find_news_item_title_text);
        mScrollNewsTextView.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                TextView textView = new TextView(getActivity());
                textView.setGravity(Gravity.CENTER);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                textView.setSingleLine(true);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                textView.setTextColor(getResources().getColor(R.color.gray_dark));
                FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                lp.gravity = Gravity.CENTER_VERTICAL;
                textView.setLayoutParams(lp);
                return textView;
            }
        });
        mScrollNewsTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.i(number + "====");
                if(mNewDynamiBean != null ){
                    if(number==0){
                        number=mNewDynamiBean.size();
                    }
                    if (mNewDynamiBean.get(number-1) != null) {
                        String url = mNewDynamiBean.get(number-1).getNew_dynami_id_url();
                        WebActivity.launchActivity(getActivity(), url);
                    }
                }

            }
        });

        mScrollNewsAllView = (TextView) view.findViewById(R.id.find_news_all_text);

        mActivityLayout = (LinearLayout) view.findViewById(R.id.find_activity_layout);
        mActionAllTv = (TextView) view.findViewById(R.id.find_action_all_text);
        mActionTitleTv = (TextView) view.findViewById(R.id.find_action_title_text);
        mActionDescTv = (TextView) view.findViewById(R.id.find_action_desc_text);
        mActionImageView = (ImageView) view.findViewById(R.id.find_action_lastest_image);

        mMedioReportAllTv = (TextView) view.findViewById(R.id.find_media_report_all_text);
        mMedioReportExpandListView = (ExpandListView) view.findViewById(R.id.find_media_report_expandListView);

        mTogetherAllTv = (TextView) view.findViewById(R.id.find_together_all_text);
        mTogetherExpandGridView = (ExpandGridView) view.findViewById(R.id.find_together_expandGridView);

        mScrollNewsAllView.setOnClickListener(clickListener);
        mMedioReportAllTv.setOnClickListener(clickListener);
        mActionAllTv.setOnClickListener(clickListener);
        mTogetherAllTv.setOnClickListener(clickListener);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.setmTitleTextView("发现");
        mainActivity.setLogoImageShow(false);

//        getDataForRemote();
    }

    private void getDataForRemote() {
        Map<String, String> map = new HashMap<String, String>();
        Xutils.getInstance().post(getActivity(), Constants.URL_FIND, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {

                BaseFindBean baseFindBean = gson.fromJson(result, BaseFindBean.class);
                FindTabBean mFindTabBean = baseFindBean.getData();
                //活动相关
                final FindTabBean.ActivitiesBean mActivityBean = mFindTabBean.getActivities();
                if (mActivityBean == null || mActivityBean.getImage() == null) {
                    mActivityLayout.setVisibility(View.GONE);
                } else {
                    mActivityLayout.setVisibility(View.VISIBLE);
                    mActionTitleTv.setText(mActivityBean.getActivity_name());
                    mActionDescTv.setText(mActivityBean.getCount() + "人参与");
                    mUrlAllAction = mActivityBean.getAll_url();
                    mActivityLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            WebActivity.launchActivity(getActivity(), mActivityBean.getUrl());
                        }
                    });
                    ImageLoader.getInstance().loadImage(mActivityBean.getImage(), MyDisplayImageOptions.getInstance(R.drawable.icon_banner_default), new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String s, View view) {
                            LogUtil.i("s:" + s);
                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {

                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {
//                            LogUtil.i(view.getMeasuredWidth()+"---"+view.getMeasuredHeight());
                            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mActionImageView.getLayoutParams();
                            WindowManager manager = getActivity().getWindowManager();
                            if (manager != null) {
                                DisplayMetrics outMetrics = new DisplayMetrics();
                                manager.getDefaultDisplay().getMetrics(outMetrics);
                                params.width = outMetrics.widthPixels;
                                params.height = outMetrics.widthPixels / (bitmap.getWidth() / bitmap.getHeight());
                                mActionImageView.setLayoutParams(params);
                                mActionImageView.setImageBitmap(bitmap);
                            }

                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {

                        }
                    });
                }

                //头部
                List<FindTabBean.FindUrlNameBean> mFindUrlNameBean = mFindTabBean.getFind_url_name();
                setTopGridViewData(mFindUrlNameBean);


                List<FindTabBean.MediaCoveragesBean> mMediaCoveragesBean = mFindTabBean.getMedia_coverages();
                setmMedioReportListView(mMediaCoveragesBean);

                mNewDynamiBean = mFindTabBean.getNew_dynami();
                if (mNewDynamiBean != null) {
                    mUrlAllNews = mNewDynamiBean.get(0).getNew_dynami_url();
                    setScrollTextViewData();
                }


                mUrlAllTogether = mFindTabBean.getCooperate();
            }

            @Override
            public void onFailer(int status, String result) {

            }

            @Override
            public void onFinish() {
                myPtrClassicFrameLayout.refreshComplete();
            }
        });


    }

    private void setTopGridViewData(final List<FindTabBean.FindUrlNameBean> beanList) {


        AdapterFindTop topAdapter = new AdapterFindTop(getActivity(), beanList);
        topGridView.setAdapter(topAdapter);
        topGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                WebActivity.launchActivity(getActivity(), beanList.get(i).getUrl());

            }
        });
    }


    private void setmMedioReportListView(final List<FindTabBean.MediaCoveragesBean> beanList) {
        mUrlAllReport = beanList.get(0).getMedia_coverages_url();
        AdapterFindReport topAdapter = new AdapterFindReport(getActivity(), beanList);
        mMedioReportExpandListView.setAdapter(topAdapter);
        mMedioReportExpandListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                WebActivity.launchActivity(getActivity(), beanList.get(i).getMedia_coverages_id_url());
            }
        });
    }


    private void setmTogetherExpandGridViewData() {

        List<FindTogetherBean> beanList = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            FindTogetherBean bean = new FindTogetherBean();
            bean.setImageRes(mTogetherRes[i]);
            beanList.add(bean);
        }

        AdapterTogether topAdapter = new AdapterTogether(getActivity(), beanList);
        mTogetherExpandGridView.setAdapter(topAdapter);
        mTogetherExpandGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
    }


    /**
     * 上拉加载
     */


    @Override
    public void onloadData(View view) {
        setmTogetherExpandGridViewData();


        myPtrClassicFrameLayout.postDelayed(new Runnable() {

            @Override
            public void run() {
                myPtrClassicFrameLayout.autoRefresh(true);
            }
        }, 150);

        myPtrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                myPtrClassicFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getDataForRemote();

                        myPtrClassicFrameLayout.setLoadMoreEnable(false);
                    }
                }, 150);
            }
        });

    }

    @Override
    public void adapterScreen() {

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void setScrollTextViewData() {
        if (mNewDynamiBean != null) {
            mScrollNewsTextView.setText(mNewDynamiBean.get(0).getName());
            mCheckMsgThread = new HandlerThread("check-message-coming");
            mCheckMsgThread.start();
            mCheckMsgHandler = new Handler(mCheckMsgThread.getLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    LogUtil.i(mCheckMsgHandler.getLooper().getThread() + "---");

                    if (isUpdateInfo) {
                        checkForUpdate(mNewDynamiBean);
//
                    }
                }
            };
            mCheckMsgHandler.sendEmptyMessage(MSG_UPDATE_INFO);
        }


    }


    /**
     * 模拟从服务器解析数据
     */
    private void checkForUpdate(final List<FindTabBean.NewDynamiBean> beanList) {
//            Thread.sleep(2000);
        LogUtil.i(beanList.size() + "===");
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                if (number == beanList.size()) {
                    number = 0;
                }
                LogUtil.i(number + "=");
                mScrollNewsTextView.setText(beanList.get(number).getName());
                mScrollNewsTextView.next();
                number = number + 1;


            }
        });
        if (!mCheckMsgHandler.hasMessages(MSG_UPDATE_INFO)) {
            mCheckMsgHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO, 2000);
        }
    }


    @Override
    public void onStop() {
        super.onStop();
        LogUtil.i("onStop");
        isUpdateInfo = false;
        if (mCheckMsgHandler != null) {
            if (mCheckMsgHandler.hasMessages(MSG_UPDATE_INFO)) {
                mCheckMsgHandler.removeMessages(MSG_UPDATE_INFO);
            }
        }
    }

    @Override
    public void resume() {
        super.resume();
        LogUtil.i("resume");
        //开始查询
        isUpdateInfo = true;
        if (mCheckMsgHandler != null) {
            if (!mCheckMsgHandler.hasMessages(MSG_UPDATE_INFO)) {
                mCheckMsgHandler.sendEmptyMessage(MSG_UPDATE_INFO);
            }
        }
    }

    View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.find_news_all_text://新闻全部
                    WebActivity.launchActivity(getActivity(), mUrlAllNews);
                    break;
                case R.id.find_action_all_text://活动全部
                    WebActivity.launchActivity(getActivity(), mUrlAllAction);
                    break;
                case R.id.find_together_all_text://合作伙伴全部
                    WebActivity.launchActivity(getActivity(), mUrlAllTogether);
                    break;
                case R.id.find_media_report_all_text://媒体报道全部
                    WebActivity.launchActivity(getActivity(), mUrlAllReport);

                    break;
            }
        }
    };
}
